<?php
namespace app\admin\controller;
use app\common\model\User;
use app\common\model\Node;
use app\common\model\MenuModel;
use think\Db;
use think\Config;
use think\Session;
use think\Request;
use com\Database;

/**
 * 用户组管理
 * @author yq
 *
 */
class Authgroup extends Base{

    /**
     * 用户组列表
     * @return mixed|string
     */
    public function index(){
        /*********************用户组管理**************************/
        $user = new User();
        $node = new Node();
        $auth_group = $user->getAllAuthGroup($this->set['auth_group'],array('status'=>1));
        //获取全部节点
        $rule = $node->getAllMenu(['status'=>1],$this->set['auth_rule']);

        $parent = []; //父类
        foreach($rule as $key=>$vo){
            if($vo['pid'] == 0){
                $parent[] = $vo;
                unset($rule[$key]);
            }
        }
        foreach ($parent as $key => $val){
            foreach ($rule as $k => $v){
                if($v['pid'] == $val['id']){
                    $parent[$key]['child'][] = $v;
                    unset($rule[$k]);
                }
            }
        }
        foreach ($parent as $key => $val){
            if(!empty($parent[$key]['child'])){
                foreach ($parent[$key]['child'] as $k => $v){
                    foreach ($rule as $kk => $vv){
                        if($v['id'] ==  $vv['pid']){
                            $parent[$key]['child'][$k]['levels'][] = $vv;
                        }
                    }
                }
            }
        }


        /********************管理员管理**********************/
        //搜索条件
        //查询字段
        $field = 'a.account,a.avatar_img,a.loginnum,a.last_login_ip,a.last_login_time,a.name,a.id,a.status,b.title,a.is_admin';
        //查询条件
        $where['a.is_delete'] = 0;
        //$where['a.a_id'] = session($this->set['db_name'].'a_id');
        //主表
        $dbname = $this->set['db_name'];
        //分表
        $sub_table = $this->set['auth_group'];
        $admin_data = $user->getInfoAll($field, $where, $dbname, $sub_table);


        /******************菜单管理**************************/
        $menu = new MenuModel();
        $admin_rule = $menu->getAllMenu($this->set['auth_rule']);
        $arr = $menu->rule($admin_rule);



        /*******************数据库备份*************************/
        $Db = Db::connect();
        $tmp = $Db->query('SHOW TABLE STATUS');
        $db_data = array_map('array_change_key_case', $tmp);


        /*********************数据库还原****************************/
        $backup_config= Config::get('db_backup');
        $path_tmp = $backup_config['data_backup_path'];
        is_dir($path_tmp) || mkdir($path_tmp, 0755, true);
        $path = realpath($path_tmp);

        $flag = \FilesystemIterator::KEY_AS_FILENAME;
        $glob = new \FilesystemIterator($path, $flag);

        $list = array();
        foreach ($glob as $name => $file) {
            if (preg_match('/^\d{8,8}-\d{6,6}-\d+\.sql(?:\.gz)?$/', $name)) {
                $name = sscanf($name, '%4s%2s%2s-%2s%2s%2s-%d');
                $date = "{$name[0]}-{$name[1]}-{$name[2]}";
                $time = "{$name[3]}:{$name[4]}:{$name[5]}";
                $part = $name[6];
                if (isset($list["{$date} {$time}"])) {
                    $info = $list["{$date} {$time}"];
                    $info['part'] = max($info['part'], $part);
                    $info['size'] = $info['size'] + $file->getSize();
                } else {
                    $info['part'] = $part;
                    $info['size'] = $file->getSize();
                }
                $extension = strtoupper(pathinfo($file->getFilename(), PATHINFO_EXTENSION));
                $info['compress'] = ($extension === 'SQL') ? '-' : $extension;
                $info['time'] = strtotime("{$date} {$time}");
                $list["{$date} {$time}"] = $info;
            }
        }


        $this->assign('dbrestore_data',$list);
        $this->assign('dbbackup_data',$db_data);
        $this->assign('menu_data',$arr);
        $this->assign(['data'=>$auth_group,'rule'=>$parent]);
        $this->assign('admin_data',$admin_data);
        return $this->fetch();
    }


    /**
     * 修改用户组状态
     */
    public function updateStatus(){
        if(request()->isPost()){
            $id = input("param.id");
            $node = new Node();
            $where = ['id'=>$id];
            $db_name = $this->set['auth_group'];
            //查询用户组数据
            $auth_group= $node->getOneAuthGroup($db_name,$where);
            if($auth_group['status'] == 1){
                $update =  $node->modify($where, ['status'=>0], $db_name);
                return json(['code' => 1, 'data' => '', 'msg' => '已禁止']);
            }else if($auth_group['status'] == 0){
                $update =  $node->modify($where, ['status'=>1], $db_name);
                return json(['code' => 1, 'data' => '', 'msg' => '已开启']);
            }
        }
    }


    /**
     * 添加用户组
     */
    public function add(){
        if(request()->isPost()){
            $data = $this->request->post();
            $node= new Node();
            //组装入库数据
            if(empty($data['status'])){
                $data['status'] = 0;
            }
            $add = $node->AddAuthgroup($this->set['auth_group'], $data);
            if($add){
                return json(['code'=>1,'msg'=>'添加成功','data'=>url('Authgroup/index')]);
            }else{
                return json(['code'=>2,'msg'=>'添加失败','data'=>'']);
            }
        }
        return $this->fetch();
    }



    /**
     * 编辑用户组
     */

    public function edit(){
        $node = new Node();
        if(request()->isPost()){
            $data = $this->request->post();
            $where['id'] = $data['id'];
            unset($data['id']);
            $res = $node->modify($where, $data, $this->set['auth_group']);
            if($res){
                return json(['code'=>1,'msg'=>'修改成功','data'=>url('Authgroup/index')]);
            }else{
                return json(['code'=>2,'msg'=>'修改失败','data'=>'']);
            }
        }
        $id = input("param.id");
        $auth_group =  $node->getOneAuthGroup($this->set['auth_group'],['id'=>$id]);
        $this->assign('data',$auth_group);
        return $this->fetch();
    }



   /**
    * 获取用户组权限节点
    */


    public function AjaxAuthority(){
        if(request()->isPost()){
            $data = $this->request->post();
            $node = new Node();
            $auth_group = $node->getOneAuthGroup($this->set['auth_group'], ['id'=>$data['id']]);
            $rules = explode(',', $auth_group['rules']);
            return json(['code'=>1,'msg'=>'','data'=>$rules]);
        }
    }



    /**
     * 添加用户组节点
     */
    public function AddRules(){
        if(request()->isPost()){
            $data = $this->request->post();
            $node = new Node();
            $rules = empty($data['rules']) ? "":implode(',',$data['rules']);
            $update =  $node->modify(['id'=>$data['id']], ['rules'=>$rules], $this->set['auth_group']);
            if($update){
                return json(['code'=>1,'msg'=>'添加节点成功','data'=>url('Authgroup/index')]);
            }else{
                return json(['code'=>2,'msg'=>'添加节点失败','data'=>'']);
            }
        }
    }







}